package com.st.security;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.st.pojo.Token;
import com.st.service.TokenService;
import com.st.utils.JWTUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class SecurityTokenImpl extends OncePerRequestFilter {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private TokenService tokenService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        Integer id = null;
        if (token != null && !token.equals("")){
            try {
                DecodedJWT decodeJWT = jwtUtil.getToken(token);
                Claim claim = decodeJWT.getClaim("id");
                id = claim.asInt();
            } catch (Exception e) {
                System.out.println("非法!");
                return;
            }
            QueryWrapper<Token> qw = new QueryWrapper<>();
            qw.eq(Token.COL_U_ID,id);
            Token one = tokenService.getOne(qw);
            String oneToken = one.getToken();
            Authentication authentication = JSONObject.parseObject(oneToken, Authentication.class);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request,response);
        }else {
            filterChain.doFilter(request,response);
        }
    }
}
